package com.share.order.config;

import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.function.Supplier;

@Component
public class CustomUserAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        String uri = context.getRequest().getRequestURI();

        // 添加无需认证的路径
        if (isExcludedPath(uri)) {
            return new AuthorizationDecision(true);
        }

        // 根据URI获取所需权限
        String[] requiredAuthorities = getRequiredAuthorities(uri);

        // 用户拥有的权限
        Authentication auth = authentication.get();
        if (auth == null || !auth.isAuthenticated()) {
            return new AuthorizationDecision(false);
        }

        Collection<? extends GrantedAuthority> userAuthorities = auth.getAuthorities();

        // 检查权限
        for (String required : requiredAuthorities) {
            for (GrantedAuthority userAuthority : userAuthorities) {
                if (userAuthority.getAuthority().equals("*:*:*") || userAuthority.getAuthority().equals(required)) {
                    return new AuthorizationDecision(true);
                }
            }
        }

        return new AuthorizationDecision(false);
    }

    /**
     * 返回不需要验证的路由
     */
    private boolean isExcludedPath(String uri) {
        return uri.equals("/order/messages1"); // 允许messages1无需权限
    }

    /**
     * 根据uri返回权限
     */
    private String[] getRequiredAuthorities(String uri) {
        return switch (uri) {
            case "/order/messages2" -> new String[]{"SCOPE_profile"};
            case "/order/messages3" -> new String[]{"SCOPE_Message"};
            case "/order/messages4" -> new String[]{"ROLE_USER"};
            default -> new String[0]; // 其他路径默认无权限要求（需根据实际情况调整）
        };
    }
}